#region Using directives
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using C4F.DevKit.Messaging;
#endregion

namespace MapiApplication
{
    public partial class MailClient : Form
    {
        #region Globals

        MapiManager objMapiManager = new MapiManager();
        List<Mail> mails = new List<Mail>();
        string toolTipToNames = string .Empty;
        string toolTipCcNames = string.Empty;
        string toolTipAttachmentNames = string.Empty;
        string toolTipSubjectNames = string.Empty;
        string toolTipFromNames = string.Empty;
        ToolTip tp = new ToolTip();
        List<string> credentialList = new List<string>();

        #endregion

        #region Constructors
        public MailClient()
        {
        }

        public MailClient(string profileName)
        {
            InitializeComponent();
            AddColumnsToGrid();
            SetColumnsWidth();
            try
            {
                objMapiManager.Logon(profileName);
                GetAllMails();
            }
            catch(MapiManagerException mapiManagerException)
            {
                MessageBox.Show(mapiManagerException.Message, "MAPI Management", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch(InvalidOperationException invalidOperationException)
            {
                MessageBox.Show(invalidOperationException.Message, "MAPI Management", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (ArgumentException argException)
            {
                MessageBox.Show(argException.Message, "MAPI Management", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        #endregion

        #region Helper Methods

        private void AddColumnsToGrid()
        {
            dgInbox.Columns.Add("Id", "Id");
            dgInbox.Columns.Add("From", "From");
            dgInbox.Columns.Add("Subject", "Subject");
            dgInbox.Columns.Add("Received", "Received");
        }

        private void SetColumnsWidth()
        {
            try
            {
                int colCount = dgInbox.ColumnCount - 1;
                if (colCount != 0)
                {
                    int colWidth = (dgInbox.Width) / colCount;
                    foreach (DataGridViewColumn d in dgInbox.Columns)
                    {
                        d.Width = colWidth;
                    }
                }
            }
            catch(Exception ex)
            {
                 MessageBox.Show(ex.Message, "MAPI Management", MessageBoxButtons.OK, 
                            MessageBoxIcon.Error);
            }
        }

        private void DeleteMail()
        {
            try
            {
                DataGridViewSelectedRowCollection row = dgInbox.SelectedRows;
                foreach (DataGridViewRow r in row)
                {
                    string id = r.Cells[0].Value.ToString();
                    objMapiManager.DeleteMail(id);
                    dgInbox.Rows.Remove(r);
                }
            }
            catch (MapiManagerException mapiException)
            {
                MessageBox.Show(mapiException.Message, "MAPI Management", MessageBoxButtons.OK,
                            MessageBoxIcon.Error);
            }
            catch (ArgumentNullException argNullException)
            {
                MessageBox.Show(argNullException.Message, "MAPI Management", MessageBoxButtons.OK,
                            MessageBoxIcon.Error);
            }
            catch (ArgumentException argException)
            {
                MessageBox.Show(argException.Message, "MAPI Management", MessageBoxButtons.OK,
                            MessageBoxIcon.Error);
            }
        }

        private void GetMailDetails()
        {
            DataGridViewSelectedRowCollection row = dgInbox.SelectedRows;
            foreach (DataGridViewRow r in row)
            {
                if (r.Cells["Id"].Value != null)
                {
                    string id = r.Cells["Id"].Value.ToString();
                    foreach (Mail m in mails)
                    {
                        if (m.Id == id)
                        {
                            lblfrom.Text = DisplayText(m.From);
                            toolTipFromNames = m.From;
                            string toNames = GetNames(m.ToList);
                            lblTo.Text = DisplayText(toNames);
                            toolTipToNames = toNames;
                            lblSubject.Text = DisplayText(m.Subject);
                            toolTipSubjectNames = m.Subject;
                            string ccNames = GetNames(m.CcList);
                            lblCc.Text = DisplayText(ccNames);
                            toolTipCcNames = ccNames;
                            txtMailBody.Text = m.MessageBody;
                            FillAttachCombo(m.Attachments);
                        }
                    }
                }
            }
        }

        private void FillAttachCombo(List<string> list)
        {
            cmbAttachments.Items.Clear();
            if (list != null)
            {
                foreach (string attachment in list)
                {
                   cmbAttachments.Items.Add(attachment);
                }
                cmbAttachments.SelectedIndex = 0;
                cmbAttachments.Enabled = true;
                btnSave.Enabled = true;
            }
            else
            {
                cmbAttachments.Enabled = false;
                btnSave.Enabled = false;
            }
        }

        private void ToolTipDisplay(Control ctl,string s)
        {
            tp.RemoveAll();
            tp.SetToolTip(ctl, s);
        }

        private string DisplayText(string str)
        {
            string returnString = string.Empty;
            int limit = 35;
            if (str != null)
            {
                if (str.Length > limit)
                {
                    returnString = str.Substring(0, limit - 3);
                    returnString += "...";
                }
                else
                {
                    return str;
                }
            }
            return returnString;
        }

        private string GetNames(List<string> list)
        {
            string names = string.Empty;
            if (list != null)
            {
                if (list.Count > 1)
                {
                    int i = 0;
                    for (; i < list.Count - 1; i++)
                    {
                        names += list[i];
                        names += ";";
                    }
                    names += list[i];
                }
                if (list.Count == 1)
                {
                    names = list[0];
                }
            }
            return names;

        }

        private void GetAllMails()
        {
            try
            {
                mails = objMapiManager.GetAvailableMails();

                foreach (Mail m in mails)
                {
                    dgInbox.Rows.Add(m.Id, m.From, m.Subject, m.Date);
                }
                dgInbox.Columns["Id"].Visible = false;
            }
            catch (MapiManagerException mapimanagerException)
            {
                MessageBox.Show(mapimanagerException.Message, "MAPI Management", MessageBoxButtons.OK, 
                            MessageBoxIcon.Error);
            }
        }

        #endregion

        #region Event Handlers

        private void MailClient_FormClosed(object sender, FormClosedEventArgs e)
        {
            try
            {
            objMapiManager.Logoff();
            }
            catch (MapiManagerException mapimanagerException)
            {
                MessageBox.Show(mapimanagerException.Message, "MAPI Management", MessageBoxButtons.OK, 
                            MessageBoxIcon.Error);
            }
            catch (InvalidOperationException invalidOperation)
            {
                MessageBox.Show(invalidOperation.Message, "MAPI Management", MessageBoxButtons.OK, 
                            MessageBoxIcon.Error);
            }
        }

        private void dgInbox_SizeChanged(object sender, EventArgs e)
        {
            SetColumnsWidth();
        }

        private void toolStripCreateNew_Click(object sender, EventArgs e)
        {
            frmCreateNew objCreateNew = new frmCreateNew(objMapiManager, ref credentialList);
            objCreateNew.Show();
        }

        private void toolStripDelete_Click(object sender, EventArgs e)
        {
            DeleteMail();
        }

        private void dgInbox_SelectionChanged(object sender, EventArgs e)
        {
            GetMailDetails();
        }

        private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                DeleteMail();
            }

            if (e.KeyCode == Keys.Escape)
                this.Close();
        }

        private void toolStripBtnReply_Click(object sender, EventArgs e)
        {
            frmCreateNew objCreateNew = new frmCreateNew(objMapiManager,lblfrom.Text,string.Empty,"Re: "+lblSubject.Text,txtMailBody.Text);
            objCreateNew.Show();
        }

        private void toolStripBtnReplyAll_Click(object sender, EventArgs e)
        {
            string replyToList = string.Empty;
            string replyCcList = string.Empty;
            
            DataGridViewSelectedRowCollection row = dgInbox.SelectedRows;
            foreach (DataGridViewRow r in row)
            {
                if (r.Cells["Id"].Value != null)
                {
                    string id = r.Cells["Id"].Value.ToString();
                    foreach (Mail m in mails)
                    {
                        if (m.Id == id)
                        {
                            if (m.From.EndsWith(";"))
                                replyToList = m.From + GetNames(m.ToList);
                            else
                                replyToList = m.From + ";" + GetNames(m.ToList);

                            replyCcList = GetNames(m.CcList);

                            frmCreateNew objCreateNew = new frmCreateNew(objMapiManager, replyToList, replyCcList, "Re: " + m.Subject, txtMailBody.Text);
                            objCreateNew.Show();
                        }
                    }
                }
            }

        }

        private void toolStripBtnRefresh_Click(object sender, EventArgs e)
        {
            dgInbox.Rows.Clear();
            GetAllMails();

        }

        private void lblfrom_MouseHover(object sender, EventArgs e)
        {           
            
            ToolTipDisplay((Control)sender, toolTipFromNames);
        }

        private void lblTo_MouseHover(object sender, EventArgs e)
        {
            ToolTipDisplay((Control)sender, toolTipToNames);
        }

        private void lblSubject_MouseHover(object sender, EventArgs e)
        {
            ToolTipDisplay((Control)sender, toolTipSubjectNames);
        }

        private void lblCc_MouseHover(object sender, EventArgs e)
        {
            ToolTipDisplay((Control)sender, toolTipCcNames);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog saveFileDialog = new FolderBrowserDialog(); 
            DataGridViewSelectedRowCollection rows = dgInbox.SelectedRows;
            saveFileDialog.Description = "Please select path to save the file:";
            saveFileDialog.ShowNewFolderButton = true;
            
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    string targetPath = saveFileDialog.SelectedPath;
                    objMapiManager.SaveAttachment(rows[0].Cells["Id"].Value.ToString(),cmbAttachments.SelectedIndex, targetPath + "\\", cmbAttachments.Text, false);
                }
                catch (MapiManagerException mapiException)
                {
                    MessageBox.Show(mapiException.Message, "MAPI Management", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                catch (ArgumentNullException argNullException)
                {
                    MessageBox.Show(argNullException.Message, "MAPI Management", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                catch (ArgumentException argException)
                {
                    MessageBox.Show(argException.Message, "MAPI Management", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        #endregion
    }
}